package com.lm.memcached.utils;

import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Component
public class MemcachedUtils {

    private final MemcachedClient client;

    @Value("${memcached.expire:600}")
    private int expireTime;

    public MemcachedUtils(MemcachedClient client) {
        this.client = client;
    }

    public void set(String key, Object value) {
        client.set(key, expireTime, value);
    }

    public Object get(String key) {
        return client.get(key);
    }

    public void delete(String key) {
        client.delete(key);
    }

    public boolean add(String key, Object value) {
        Future<Boolean> future = client.add(key, expireTime, value);
        try {
            return future.get(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            return false;
        }
    }
}

